package com.yang.strategy.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author yangyongsheng
 * @date 2024/9/7 23:16
 * @description
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    /**
     * 通过bean名称在IOC容器中获取实例
     * @param beanName
     * @return
     */
    public static Object getBeanByName(String beanName){
        return SpringUtil.applicationContext.getBean(beanName);
    }

    /**
     * 通过Class对象在IOC容器中获取实例
     * @param clazz
     * @return
     */
    public static Object getBeanByClass(Class clazz){
        return SpringUtil.applicationContext.getBean(clazz);
    }
}
